<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/9/10
 * Time: 22:20
 */

namespace App\Providers;


class Curl
{
    /**
     * 发送请求
     *
     * @param string $url      请求地址
     * @param array  $data  请求内容
     * @return string 应答json字符串
     */
    public static function get($url, $data)
    {

        return self::sendCurl($url, $data, 'get');
    }

    /**
     * 发送请求
     *
     * @param string $url      请求地址
     * @param array  $data  请求内容
     * @return string 应答json字符串
     */
    public static function post($url, $data)
    {

        return self::sendCurl($url, $data, 'post');
    }

    /**
     * 发送请求
     *
     * @param string $url      请求地址
     * @param array  $data  请求内容
     * @param string  $method  请求方式
     * @return string 应答json字符串
     */
    private static function sendCurl($url, $data, $method = 'get') {
        $ch = curl_init();
        if ($method === 'get') {
            if ($data) {
                $query = http_build_query($data);
                $url .= '?' . $query;
            }
        } else {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

        $ret = curl_exec($ch);

        if (false == $ret) {
            // curl_exec failed
            $result = ['body' => [], 'status' => 404, 'message' => curl_error($ch)];
        } else {
            $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = ['body' => [], 'status' => 403, 'message' => $rsp." ".curl_error($ch)];
            } else {
                $result = json_decode($ret, true);
            }
        }

        curl_close($ch);

        return $result;
    }

    /**
     * 使用方法:
     * ServiceApi::postV1('/signup/check', ['account' => '13800138000']);
     * ServiceApi::getV1(...);
     * ServiceApi::getV2(...);
     * ServiceApi::putV3(...);
     *
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws \Exception
     */
    public static function __callStatic($name, $arguments)
    {
        preg_match('/(get|post|put|patch|delete|head|connect|options|trace)V(\d)/', $name, $matches);
        $method = array_key_exists(1, $matches) ? $matches[1] : null;
        $version = array_key_exists(2, $matches) ? $matches[2] : null;

        array_unshift($arguments, $method);
        array_unshift($arguments, $version);

        if ($method && $version) {
            return call_user_func_array(['self', 'request'], $arguments);
        } else {
            throw new \Exception('Curl SDK ERROR: http method not exist');
        }
    }
}